/**
 * Stream API
 */
var Stream = (() => {
    func createStream(first, remain) {
        var s = {
            first,
            remain,
            forEach(consumer) {
                forEach(s, consumer)
            },
            toList() {
                return toList(s)
            },
            map(mapper) {
                return map(s, mapper)
            },
            filter(predicate) {
                return filter(s, predicate)
            }
        }
        return s
    }

    func forEach(s, consumer) {
        while (s != EMPTY_STREAM) {
            consumer(s.first)
            s = s.remain
        }
    }

    func toList(s) {
        var list = []
        while (s != EMPTY_STREAM) {
            list.addLast(s.first)
            s = s.remain
        }
        return list
    }

    func map(s, mapper) {
        if (s == EMPTY_STREAM) {
            return EMPTY_STREAM
        }
        return createStream(mapper(s.first), map(s.remain, mapper))
    }

    func filter(s, predicate) {
        if (s == EMPTY_STREAM) {
            return EMPTY_STREAM
        }
        if (predicate(s.first)) {
            return createStream(s.first, filter(s.remain, predicate))
        }
        return filter(s.remain, predicate)
    }

    var EMPTY_STREAM = createStream(null, null)

    func fromList(list) {
        func _fromList(index) {
            if (index == list.length()) {
                return EMPTY_STREAM
            }
            return createStream(list[index], _fromList(index + 1))
        }
        return _fromList(0)
    }

    return {
        // 从列表生成流
        of(list) {
            return fromList(list)
        }
    }
})()
